package yf.mall.controller.api;

import com.github.pagehelper.PageHelper;
import com.yf.annotation.IgnoreAuth;
import com.yf.annotation.LoginUserId;
import com.yf.annotation.SysLog;
import com.yf.response.RRException;
import com.yf.utils.ShiroUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import yf.mall.common.Const;
import yf.mall.dao.DocDownDao;
import yf.mall.dao.LevelDao;
import yf.mall.dao.StoresDao;
import yf.mall.entity.*;
import com.yf.response.R;
import yf.mall.enums.*;
import yf.mall.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import yf.mall.vo.ActGoodsVo;
import yf.mall.vo.PriceVo;

import java.util.*;
import java.util.stream.Collectors;

@RequestMapping("/api/goods")
@RestController
public class ApiGoodsController {

    @Autowired
    private MallGoodsService mallGoodsService;

    @Autowired
    private MallTypeService mallTypeService;

    @Autowired
    private MallActService mallActService;

    @Autowired
    private GoodsGroupService goodsGroupService;

    /**
     * 开团
     * @param userId
     * @param goodsId
     * @return
     */
    @PostMapping("/group")
    public R group(@LoginUserId Long userId, Long goodsId) {
        GoodsGroupEntity goodsGroupEntity = goodsGroupService.addGroup(userId, goodsId);
        return R.ok(goodsGroupEntity);
    }

    //售卖类型查询
    @GetMapping("/sale")
    public R listAgent(@LoginUserId Long userId, Long saleTypeId) {
        //查出所有代理的产品
        List result = mallGoodsService.mapBySaleType(userId, saleTypeId);
        return R.ok(result);
    }

    @GetMapping("/list")
    public R list(@LoginUserId Long userId, int page, @RequestParam(required = false) Integer saleType, int limit, @RequestParam(required = false) Integer type, String order) {
        if (order == null) {
            order = "sort,id Asc";
        }
        //Sort正排序  ID反排序
        PageHelper.startPage(page, limit).setOrderBy(order);
        Map map = new HashMap();
//        map.put("homeFlag", "true");
        map.put("shelf", MallGoodsShelfEnum.ON.getIndex());//已上架
        if (saleType == null) {
            map.put("saleType", MallGoodsSaleTypeEnum.RETAIL.getIndex());
        } else {
            map.put("saleType", saleType);
        }
        List<MallGoodsEntity> mallGoodsEntities;
        if (type == null || type == 0) {
            mallGoodsEntities = mallGoodsService.queryList(map);
        } else {
            //此操作是首页tab分类 一级分类没有数据时 显示所有二级分类下的商品
            mallGoodsEntities = homeType(type);
        }
        mallGoodsEntities = mallGoodsEntities.stream().filter(m -> m.getDailySel() == null || m.getDailySel() == 0).collect(Collectors.toList());
        // 根据级别筛选
        mallGoodsEntities = mallGoodsService.filterByLevel(userId, mallGoodsEntities);
        //获取活动
        getAct(mallGoodsEntities);
        //获取所属店铺
        return R.ok(mallGoodsEntities);
    }

    /**
     * 查询所有分类
     *
     * @param params
     * @return
     */
    @RequestMapping("/type")
    @IgnoreAuth
    public R typeList(@RequestParam Map<String, Object> params) {
        PageHelper.orderBy("sort");
        List<MallTypeEntity> mallTypeEntities = mallTypeService.queryList(params);
        return R.ok(mallTypeEntities);
    }

    /**
     * 根据产品名查询
     *
     * @param
     * @return
     */
    @RequestMapping("/search")
    public R search(@LoginUserId Long userId, String name, int page, int limit) {
        String order = "sort,id Asc";
        PageHelper.startPage(page, limit).setOrderBy(order);
        List<MallGoodsEntity> goodsEntityList = mallGoodsService.searchName(name);
        getAct(goodsEntityList);
        //获取所属店铺
        if (goodsEntityList != null && goodsEntityList.size() > 0) {
            for (MallGoodsEntity mallGoodsEntity : goodsEntityList) {
                if (mallGoodsEntity.getUserId() != null) {
                    ShopEntity shopEntity = shopService.findByUserId(mallGoodsEntity.getUserId());
                    mallGoodsEntity.setShopEntity(shopEntity);
                }
            }
        }
        goodsEntityList = mallGoodsService.filterByLevel(userId, goodsEntityList);

        return R.ok(goodsEntityList);
    }

    @Autowired
    private SaleTypeInfoService saleTypeInfoService;

    //quequnlong 获取售卖类型和是否在直播中
    private void getAct(List<MallGoodsEntity> mallGoodsEntities) {
        for (MallGoodsEntity mallGoodsEntity : mallGoodsEntities) {
            SaleTypeInfoEntity saleTypeInfoEntity = saleTypeInfoService.findByGoodsId(mallGoodsEntity.getId());
            if (null != saleTypeInfoEntity) {
                mallGoodsEntity.setAct(saleTypeInfoEntity);
            }
            Long userId = mallGoodsEntity.getUserId();
            //获取店铺信息 不是公司的产品
            if (userId != null && !userId.equals(Const.ADMIN_ID)) {
                ShopEntity shopEntity = shopService.findByUserId(userId);
                if (shopEntity != null) {
                    mallGoodsEntity.setShopEntity(shopEntity);
                }
            }
        }
    }

    @Autowired
    private ShopService shopService;


    @Autowired
    private StoresDao storesDao;

    @Autowired
    private LevelDao levelDao;
    @Autowired
    private DocDownDao docDownDao;

    /**
     * que
     * 进货价格表
     *
     * @param
     * @return
     */
    @RequestMapping("/priceTable")
    public R priceTable(@LoginUserId Long userId, Long goodId) {
        List<PriceVo> priceVos = mallGoodsService.priceTable(userId, goodId);
        LevelEntity level = this.levelDao.findByUserId(userId);
        MallGoodsEntity mallGoodsEntity = new MallGoodsEntity();
        if (level.getLv() <= 6) {
            mallGoodsEntity = this.mallGoodsService.get(goodId);
        }
        if (mallGoodsEntity.getRemark() != null && mallGoodsEntity.getRemark().contains(".")) {
            priceVos = new ArrayList<>();
        }
        return R.ok(priceVos).putExtra("shopPrice", mallGoodsEntity.getShopPrice());
    }

    @RequestMapping("/docDown")
    public R getDocDown(@LoginUserId Long userId, Long goodsId) {
        List<DocDownEntity> list = docDownDao.queryByGoodsId(goodsId, DocDownStatusEnum.YES.getIndex());
        return R.ok(list);
    }

    // quequnlong  此操作是首页tab分类 一级分类没有数据时 显示所有二级分类下的商品
    public List<MallGoodsEntity> homeType(Integer type) {

        Long typeId = type.longValue();
        List<MallGoodsEntity> list = null;

        if (type != null) {
            list = mallTypeService.findTypeByPid(typeId, MallGoodsShelfEnum.ON.getIndex());
           /* //获取该一级分类下的二级分类
            List<MallTypeEntity> parentType = mallTypeService.findByParentId(typeId);
            for (MallTypeEntity mallTypeEntity : parentType) {
                //根据分类获取产品id集合
                List<Long> goodsIds = mallTypeService.findByType(mallTypeEntity.getId());
                if (goodsIds != null && goodsIds.size() > 0){
                    for (Long goodId : goodsIds) {
                        System.out.println(goodId);
                        MallGoodsEntity mallGoodsEntity = mallGoodsService.get(goodId);
                        if (mallGoodsEntity ==null){
                            continue;
                        }
                        if (mallGoodsEntity.getShelf() != null && MallGoodsShelfEnum.ON.getIndex() == mallGoodsEntity.getShelf()){
                            list.add(mallGoodsEntity);
                        }
                    }
                }
            }*/
        }
        list.sort((o1, o2) -> {
            if (null != o1.getSort() && null != o2.getSort()) {
                if (o1.getSort() > o2.getSort()) {
                    return 1;
                }
            }
            return -1;
        });
        return list;
    }
}
